extends Label

var sentence = []
var isChat = false
var sentenceIndex = 0
var chatIndex = 0
var minSpeed = 0
var maxSpeed = 0

@onready var timer = $TalkTimer
@onready var sound = $TalkSound

signal chatComplete

func _ready():
	timer.start()
	timer.connect("timeout", timeout)


func addChat(chat, minSpeed, maxSpeed):
	# 每次说话之前, 将文本内容清空
	text = ""
	visible = true
	isChat = true
	chatIndex = 0
	if typeof(chat) == TYPE_STRING:
		self.sentence.append(chat)
		
	elif typeof(chat) == TYPE_ARRAY:
		for item in chat:
			self.sentence.append(item)
		
	self.minSpeed = minSpeed
	self.maxSpeed = maxSpeed


func timeout():
	if isChat:
		var chat = sentence[sentenceIndex]
		
		# 流式输出, 一个一个字输出
		chatIndex += 1
		text = chat.substr(0, chatIndex)
		sound.start()
		# 随机等待一段时间, 继续输出下一个字
		timer.wait_time = randf_range(minSpeed, maxSpeed)
		
		if chatIndex == len(chat) - 1:
			timer.wait_time = 1
			
		if chatIndex == len(chat):
			sentenceIndex += 1
			chatIndex = 0
			
		if sentenceIndex == len(sentence):
			isChat = false
			# 触发说话完成的事件
			chatComplete.emit()
